package io.admin.modules.sys.controller;

import com.alibaba.excel.util.DateUtils;
import io.admin.common.annotation.LogOperation;
import io.admin.common.constant.Constant;
import io.admin.common.page.PageData;
import io.admin.common.utils.ExcelUtils;
import io.admin.common.utils.Result;
import io.admin.common.utils.StringUtils;
import io.admin.common.validator.AssertUtils;
import io.admin.common.validator.ValidatorUtils;
import io.admin.common.validator.group.AddGroup;
import io.admin.common.validator.group.DefaultGroup;
import io.admin.common.validator.group.UpdateGroup;
import io.admin.modules.security.user.SecurityUser;
import io.admin.modules.security.user.UserDetail;
import io.admin.modules.sys.dto.EquipmentDTO;
import io.admin.modules.sys.dto.ProjectCountDTO;
import io.admin.modules.sys.dto.ProjectDTO;
import io.admin.modules.sys.excel.ProjectExcel;
import io.admin.modules.sys.service.LineService;
import io.admin.modules.sys.service.ProjectService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 项目表
 *
 * @author Mark sunlightcs@gmail.com
 * @since 1.0.0 2024-07-06
 */
@RestController
@RequestMapping("sysproject/project")
@Api(tags="项目表")
public class ProjectController {
    @Autowired
    private ProjectService projectService;

    @Autowired
    private LineService lineService;
    @GetMapping("page")
    @ApiOperation("分页")
    @ApiImplicitParams({
        @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType="int") ,
        @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query",required = true, dataType="int") ,
        @ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType="String") ,
        @ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType="String")
    })
    public Result<PageData<ProjectDTO>> page(@ApiIgnore @RequestParam Map<String, Object> params){
        PageData<ProjectDTO> page = projectService.page(params);
        return new Result<PageData<ProjectDTO>>().ok(page);
    }

    @GetMapping("{id}")
    @ApiOperation("信息")
    public Result<ProjectDTO> get(@PathVariable("id") Long id){
        ProjectDTO data = projectService.get(id);
        return new Result<ProjectDTO>().ok(data);
    }

    @PostMapping
    @ApiOperation("保存")
    @LogOperation("保存")
    public Result save(@RequestBody ProjectDTO dto) throws ParseException {
        //效验数据
        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);
        ProjectDTO projectDTO =projectService.findProByParam(dto);
        if(null != projectDTO  ){
           return new Result().error("当前项目名称重复了，请重新修改了在提交");
        }
        dto.setEndDate(DateUtils.parseDate(dto.getEndDateStr()));
        dto.setStartDate(DateUtils.parseDate(dto.getStartDateStr()));
        dto.setState(0);
        dto.setCreateDate(new Date());
        projectService.save(dto);
        return new Result();
    }

    @PutMapping
    @ApiOperation("修改")
    @LogOperation("修改")
    public Result update(@RequestBody ProjectDTO dto)throws ParseException {
        //效验数据
        ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);
        if(StringUtils.isNotBlank(dto.getEndDateStr())){
            dto.setEndDate(DateUtils.parseDate(dto.getEndDateStr()));
        }
        if(StringUtils.isNotBlank(dto.getStartDateStr())){
            dto.setStartDate(DateUtils.parseDate(dto.getStartDateStr()));
        }
         if(!StringUtils.isBlank(dto.getIsExamine())){
             //登录用户信息
             UserDetail user = SecurityUser.getUser();
             dto.setAcceptanceDate(new Date());
             dto.setAdminUserId(user.getId());
             dto.setAdminUserName(user.getRealName());
             if(dto.getExamineState().equals(3)){
                 dto.setState(0);
             }
             if(dto.getExamineState().equals(2)){
                 dto.setState(2);
             }
         }
        ProjectDTO projectDTO =projectService.findProByParam(dto);
        if(null != projectDTO  ){
            if(!projectDTO.getId().equals(dto.getId())){
                return new Result().error("当前项目名称重复了，请重新修改了在提交");
            }
        }
        projectService.update(dto);
        if(!StringUtils.isBlank(dto.getIsExamine())){
            projectService.updateProjectByMsg(dto.getId(), dto.getExamineState(),dto.getName(),dto.getExamineNotes());
        }
        return new Result();
    }

    @DeleteMapping
    @ApiOperation("删除")
    @LogOperation("删除")
    public Result delete(@RequestBody Long[] ids){
        //效验数据
        AssertUtils.isArrayEmpty(ids, "id");
        Map<String,Object> map=new HashMap<>(1);
        map.put("projectId",String.valueOf(ids[0]));
        if(lineService.list(map).size()==0){
            projectService.delete(ids);
            return new Result();
        }else{
            return new Result().error("该项目下有线路，请先删除线路！");
        }
    }

    @GetMapping("export")
    @ApiOperation("导出")
    @LogOperation("导出")
    public void export(@ApiIgnore @RequestParam Map<String, Object> params, HttpServletResponse response) throws Exception {
        List<ProjectDTO> list = projectService.list(params);
        ExcelUtils.exportExcelToTarget(response, null, "项目表", list, ProjectExcel.class);
    }

    @RequestMapping("/copyProject")
    public Result saveCopyProject(HttpServletRequest request, HttpServletResponse response){
        String projectName = request.getParameter("name");
        String thisProjectId = request.getParameter("projectId");
        ProjectDTO dto =new ProjectDTO();
        dto.setName(projectName);
        ProjectDTO projectDTO =projectService.findProByParam(dto);
        if(null != projectDTO  ){
           return new Result().error("当前项目名称重复了，请重新修改了在提交");
        }
        projectService.saveCopyProject(projectName,thisProjectId);
        return new Result<>().ok("");
    }

    @RequestMapping("/listProTree")
    public  Result listProTree(HttpServletRequest request, HttpServletResponse response){
        return new  Result<>().ok(projectService.listProTree());
    }

    @RequestMapping("/listProCount")
    public  Result listProCount(HttpServletRequest request, HttpServletResponse response){
        return new  Result<>().ok(projectService.listProCount());
    }

}